package tree;

public class Transition {

    private Node root;

    public void add(Node node){
        if (root==null){
            this.root=node;
        }else {
            root.addNode(node);
        }
    }

    //调用中序遍历的方法
    public void infixOrder() {
        if (root == null) {
            System.out.println("根节点为空，无法遍历");
        } else {
            root.infixOrder();
        }
    }



    public static void main(String[] args) {
        int[] arr = {7, 3, 10, 12, 5, 1, 9, 2};
        Transition transition=new Transition();
        for (int i=0;i<arr.length;i++){
            transition.add(new Node(arr[i]));
        }

        transition.infixOrder();
    }

}

class Node {
    public int val;
    public Node left;
    public Node right;

    public Node(int val, Node left, Node right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public Node(int val) {
        this.val = val;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "Node{" +
                "val=" + val +
                ", left=" + left +
                ", right=" + right +
                '}';
    }

    public void addNode(Node node) {
        //如果传入的节点为空,直接返回
        if (node == null) {
            return;
        }

        if (node.val < this.val) {
            //如果节点没有叶子结点
            if (this.left == null) {
                this.left = node;
            } else {
                this.left.addNode(node);
            }
        } else {
            //添加的节点大于当前节点 放右边
            if (this.right == null) {
                this.right = node;
            } else {
                this.right.addNode(node);
            }
        }

    }

    //中序遍历
    public void infixOrder() {
        if (this.left != null) {
            this.left.infixOrder();
        }
        if (this.right != null) {
            this.right.infixOrder();
        }
        System.out.println(this);
    }


}
